package com.esdk.utils;

import com.esdk.esdk;
import com.esdk.exception.SdkRuntimeException;
import lombok.NonNull;

import java.lang.reflect.Field;

@SuppressWarnings("ALL")
public class EasyEnum{

  public static <T extends Enum> boolean contains(T obj, T ...arr){
    if(obj == null) return false;
    if(esdk.obj.isEmpty(arr)) return true;
    return esdk.array.contains(arr, obj);
  }

  public static <T extends Enum> boolean contains(@NonNull MethodReference<T, Integer> func, Integer val, T ...arr){
    return contains(map(func, val), arr);
  }

  public static <T extends Enum> boolean contains(@NonNull MethodReference<T, String> func, String val, T ...arr){
    return contains(map(func, val), arr);
  }

  public static <T extends Enum> T map(@NonNull MethodReference<T, Integer> func,Integer val){
    if(val == null) return null;
    try {
      for (Field field : func.getTargetClass().getFields()) {
        T enumObj = (T) field.get(null);
        if(esdk.obj.equals(val, func.invoke(enumObj))){
          return enumObj;
        }
      }
      return null;
    }catch(Exception e){
      throw new SdkRuntimeException(e);
    }
  }

  public static <T extends Enum> T map(@NonNull MethodReference<T, String> func, String val){
    if(esdk.str.isBlank(val)) return null;
    // 下划线 -> 驼峰 -> 全大写
    String camelCase = esdk.str.toCamelCase(val.trim()).toUpperCase();
    try {
      for (Field field : func.getTargetClass().getFields()) {
        T enumObj = (T) field.get(null);
        if(camelCase.equals(esdk.str.toCamelCase(func.invoke(enumObj)).toUpperCase())){
          return enumObj;
        }
      }
      return null;
    }catch(Exception e){
      throw new SdkRuntimeException(e);
    }
  }


  public static <T extends Enum> T mapOr(@NonNull MethodReference<T, Integer> func, Integer val, @NonNull T def){
    return esdk.obj.or(map(func,val), def);
  }


  public static <T extends Enum> T mapOr(@NonNull MethodReference<T, String> func, String val, @NonNull T def){
    return esdk.obj.or(map(func,val), def);
  }

}
